﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace HDS.Common.Helper
{
    /// <summary>
    /// appsettings.json操作类
    /// </summary>
    public class AppSettings
    {
        public static IConfiguration AppSettingConfig { get; set; }
        public static IConfiguration CustomConfig { get; set; }

        public AppSettings(string basePath = "")
        {
            basePath = string.IsNullOrWhiteSpace(basePath) ? AppContext.BaseDirectory : Path.Combine(AppContext.BaseDirectory, basePath);

            AppSettingConfig = new ConfigurationBuilder()
               .SetBasePath(basePath)
               .Add(new JsonConfigurationSource { Path = "appsettings.json", Optional = false, ReloadOnChange = false })
               .Build();
            LoadCustomConfig();
        }

        public AppSettings(IConfiguration configuration)
        {
            AppSettingConfig = configuration;
            LoadCustomConfig();
        }

        /// <summary>
        /// 获取appsettings.json配置值
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string GetAppSettingValue(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return AppSettingConfig[string.Join(":", sections)];
                }
            }
            catch (Exception)
            {
                throw;
            }

            return "";
        }

        /// <summary>
        /// 获取自定义配置值
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string GetCustomValue(params string[] sections)
        {
            try
            {
                if (sections.Any())
                {
                    return CustomConfig[string.Join(":", sections)];
                }
            }
            catch (Exception)
            {
                throw;
            }

            return "";
        }

        /// <summary>
        /// 加载Json自定义配置文件对象
        /// </summary>
        /// <param name="configFileName">配置文件名</param>
        /// <param name="basePath">基路径</param>
        /// <returns></returns>
        private void LoadCustomConfig()
        {
            // 获取程序目录下的所有配置文件
            var jsonFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.json", SearchOption.TopDirectoryOnly)
                .Union(
                    Directory.GetFiles(Directory.GetCurrentDirectory(), "*.json", SearchOption.TopDirectoryOnly)
                )
                .Where(u => !excludeJsons.Contains(Path.GetFileName(u)) && !runtimeJsonSuffixs.Any(j => u.EndsWith(j)));

            if (!jsonFiles.Any()) return;

            var config = new ConfigurationBuilder();
            foreach (var jsonFile in jsonFiles)
            {
                config.AddJsonFile(jsonFile, optional: true, reloadOnChange: false);
            }

            CustomConfig = config.Build();
        }

        /// <summary>
        /// 默认排除配置项
        /// </summary>
        private static readonly string[] excludeJsons = new[] {
            "appsettings.json",
            "appsettings.Development.json",
            "appsettings.Production.json",
        };

        /// <summary>
        /// 运行时 Json 后缀
        /// </summary>
        private static readonly string[] runtimeJsonSuffixs = new[]
        {
            "deps.json",
            "runtimeconfig.dev.json",
            "runtimeconfig.prod.json",
            "runtimeconfig.json"
        };
    }
}
